<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">

<link href="css/redmond/jquery-ui-1.10.3.custom.min.css" rel="stylesheet" type="text/css">	<!-- jquery UI CSS -->
<link href="css/zTreeStyle/zTreeStyle.css" rel="stylesheet" type="text/css">					<!-- zTree CSS函式庫 -->
<link href="css/selfTemplate.css" rel="stylesheet" type="text/css">							<!-- homemade CSS -->

<script src="js/jquery-2.1.0.min.js" type="text/javascript"></script>						<!-- jquery -->
<script src="js/jquery-ui-1.10.3.custom.js" type="text/javascript"></script>				<!-- jquery UI -->
<script src="js/jquery.ztree.core-3.5.min.js" type="text/javascript"></script>				<!-- zTree 的核心函式庫，選擇SVN用 -->
<script src="js/jquery.ztree.excheck-3.5.min.js" type="text/javascript"></script>			<!-- zTree 的延伸函式庫，選擇SVN用 -->
<script src="js/jquery.cookie.js" type="text/javascript"></script>							<!-- cookie -->
<script src="js/widgets.js" type="text/javascript"></script>								<!-- homemade js -->

<script type="text/javascript">

var setting = { check:{ enable:true},data:{simpleData: {enable:true}} };

function changeTargetSys() {
	//取得交付對象下相關的子系統
	$.ajax({type:"post",url:"QuerySys2Subsys",dataType: "json",async:false,
		data:{sysSN:$("#targetSystem option:selected").val()},
		success : function(reses) {
			$("select#subsysId option").remove();
			$.each(reses, function(i,res){
				var tmp = "<option value='"+res.s1+"'>"+res.s2+"</option>";
				$("select#subsysId").append(tmp);
			});
		},error : function(xhr, ajaxOptions, thrownError) { errorAjx(xhr); }
	});
	changeSubsys();
}

function changeSubsys() {
	$.ajax({type:"post",url:"QuerySVNconnectionInfo",dataType: "json",async:false,
		data:{subsysId:$("select#subsysId option:selected").val()},
		success : function(reses) {
			$("select#svnHost option").remove();
			$.each(reses, function(i,res){
				var tmp = "<option url='"+res.s1+"' usr='"+res.s2+"' pwd='"+res.s3+"' value='"+res.s5+"'>"+res.s4+"</option>";
				$("select#svnHost").append(tmp);
				if( i==0 ) {
					$("input:first").val( res.s1 ).prop("size",(res.s1).length);
					$("input:eq(1)").val( res.s2 ).prop("size",(res.s2).length);
					$("input:eq(2)").val( res.s3 ).prop("size",(res.s3).length*2);
				}
			});
		},error : function(xhr, ajaxOptions, thrownError) { errorAjx(xhr); }
	});
}

function changeSVNinf() {
	var url = $("select#svnHost option:selected").attr("url");
	var usr = $("select#svnHost option:selected").attr("usr");
	var pwd = $("select#svnHost option:selected").attr("pwd");

	$("input:first").val( url ).prop("size",url.length );
	$("input:eq(1)").val( usr ).prop("size",usr.length );
	$("input:eq(2)").val( pwd ).prop("size",pwd.length*2 );
}

function isProcess(str) {
	return (typeof str !== "undefined" && str != null && str!="" );
}

function insertRelatedReq(exeVer) {
	$.ajax({type:"post",url:"GetBindingReqirement",dataType:"json",async:false,
		data:{exeVer:exeVer},
		success : function(reses) {
			$.each(reses, function(i,req) {
				var isNotExist = true;
				$("#tbodyReqs input").each(function(j){
					if (  $(this).val() == req.s1 ) {
						isNotExist = false;
					}
				});
				if( isNotExist ) {
					var tmp="<tr class='req'><td class='center engN'><button type='button' onclick='removeReq(this)'>-</button></td><td class='idx int center'>"+($("#tbodyReqs tr").size()+1)+"</td><th><input class='engN' type='text' size='14' value='"+req.s1+"'/></th><th class='zhTwN'><textarea cols='100'>"+req.s2+"</textarea></th></tr>"
					$("#tbodyReqs").append(tmp);
				}
			});
			refreshUI(1,"tbodyReqs",false);
		},error : function(xhr, ajaxOptions, thrownError) { errorAjx(xhr); }
	});
}

//取得指定檔案的歷屆變更
function getFileHistoryRevision(isMR,url,usr,pwd,relativePath,fileName){
	var verSets;
	
	$.ajax({type:"post",url:"ChkFileRevision",dataType:"json",async:false,
		data:{isMR:isMR,url:url,usr:usr,pwd:pwd,relativePath:relativePath,fileName:fileName},
		success : function(reses) {
			verSets = reses;
		},error : function(xhr, ajaxOptions, thrownError) { errorAjx(xhr); }
	});
	
	return verSets;
}

function removeReq(obj) {
	$(obj).parent().parent().remove();
	refreshUI(1,"tbodyReqs",true);
}


/** 點選欲提交的檔案 **/
function selSVNfile(svnType,modId) {
	clearErrorMsg();
	windowFreeze();
	var subsysId = $("select#subsysId").val();
	
	//先確定該子系統 的SVN 連線無誤，再進行抓取
	// 0 無進行測試 1 沒有為此子系統設定 2 主機不能連 3 帳密不通  4 連線正常
	var svnUrl = $("#svnURL").val();
	var svnId = $("#svnID").val();
	var svnPwd = $("#svnPWD").val();
	
	var res= chkSVNconnection(svnUrl, svnId, svnPwd );
	
	if (res==0) {
		errorMsgShow("SVN連線發生問題，請洽系統人員");
	} else if (res==1) {
		errorMsgShow("沒有為此子系統設定SVN，請洽系統人員");
	} else if (res==2) {
		errorMsgShow("所設定的主機連線失敗，請洽系統人員");
	} else if (res==3) {
		errorMsgShow("所設定的帳密登入失敗，請洽系統人員");
	} else {	//連線成功
		var isMR = (svnType=="MR")?true:false;
	
		$.ajax({ type:'post',url:'QueryFile4Deliver',dataType:'text',async:false,
			data: {subsysId:$("select#subsysId").val(),svnUrl:svnUrl,is4Dep:true,svnId:svnId,svnPwd:svnPwd }, //送出子系統，以確定要使用該子系統的SVN
			success : function(reses) {
				if ( reses.length != 3 ) {	//因為servlet那裡這樣寫，所以回傳 "]" 表示沒有找到
					reses = reses.substring(1,(reses.length-1));
					
					$.fn.zTree.init( $("#treeDirectory"),setting, JSON.parse(reses) );
					var treeObj = $.fn.zTree.getZTreeObj("treeDirectory");
					treeObj.expandAll(false);
					$("#dialogSVNdirectory").prop("title","選擇SVN路徑").css("visibility", "visible").dialog({
						resizable:true,width:300,modal:true,show:"fold",hide:"fold",
						buttons : {
							"確定" : function() {
								
						        var nodes = treeObj.getCheckedNodes(true);
						        
								var resultStr = "";	//解析繳交註解時，最後給使用者看的字串
							
						        $(nodes).each(function(i){
						        	if ( (this.icon).indexOf("file") !== -1 ) {	//只要檔案的node, 不要資料夾的node
						        		var fileId = this.id;
										var fileName = this.name;
										
						        		if ( $("#tbodySVNF td[title='"+fileId+"']").size() == 0){	//不加重覆的檔案
						        			var relativePath = "";
											
											var folderPath = (fileId).substring(0,(fileId).lastIndexOf(fileName));
											if ( folderPath != "" ) {
												relativePath += folderPath;	
											}
											//取得歷代版次
											var verSets = getFileHistoryRevision(false,svnUrl,svnId,svnPwd,relativePath,fileName);
						        			if( verSets.length > 0 ) {
						        				var idx= $("#tbodySVNF > tr").size()+1;
												var tmp = "<tr class='fileInfo rowSVNF"+idx+"'>"+
												"<td class='center'><button id='"+idx+"' onclick=\"removeRow(this,'SVNF')\" value='"+fileId+"' type='button'>-</button></td>"+
												"<td class='idx'>"+idx+"</td>"+
												"<td><select id='"+replaceDot(fileId)+"'></select></td>"+
												"<td title='"+fileId+"' class='engN'>"+fileName+"</td>"+
												"</tr>";
												$("#tbodySVNF").append(tmp);
											
												$.each(verSets, function(j,res) {
													var tmp = "<option value='"+res.l1+"'>"+res.l1+"</option>";
													$("#tbodySVNF select#"+replaceDot(fileId) ).append(tmp);
												});
											
												//取得目前版次的相關需求
												insertRelatedReq( $("#tbodySVNF select:last option:selected").html() );
											} else {
												$("#errShortMsg").html("目前檔案"+fileName+"尚無部署於QA環境之記錄！");										
											}
						        		} else {
						        			resultStr += "\n\n檔案："+fileId+"已存在清單中！";
						        		}
						        	}
								});
						        
						        if ( isProcess(resultStr) ) {
						        	alert(resultStr);
						        }
						        refreshUI(1,"tbodySVNF",false);
								$(this).dialog("close");
							},"關閉" :function() {
								$(this).dialog("close");
							}
						}
					});
				} else {
					alert(modId+"在"+svnType+"的資料夾為空!");
				}
			}, error : function(xhr, ajaxOptions, thrownError) { errorAjx(xhr); }
		});
	} // end of else
	$("#resSVN4subsys").val("0");	//執行完驗證，將它重設為未測試的狀態，即0
	windowUnfreeze();
}

$(document).ready(function() {
	var pageName ="sdelv.html"; 
	init(pageName);
	
	//取得交付對象的清單
	$.ajax({type:"post",url:"GetSystemList",dataType: "json",async:false,
		success : function(reses) {
			$("#targetSystem option").remove();
			$.each(reses, function(i,res){
				var tmp = "<option value='"+res.i1+"'>"+res.s1+"</option>";
				$("#targetSystem").append(tmp);
			});
		},error : function(xhr, ajaxOptions, thrownError) { errorAjx(xhr); }
	});
	
	//取得交付對象下相關的子系統
	$.ajax({type:"post",url:"QuerySys2Subsys",dataType: "json",async:false,
		data:{sysSN:$("#targetSystem option:selected").val()},
		success : function(reses) {
			$("select#subsysId option").remove();
			$.each(reses, function(i,res){
				var tmp = "<option value='"+res.s1+"'>"+res.s2+"</option>";
				$("select#subsysId").append(tmp);
			});
		},error : function(xhr, ajaxOptions, thrownError) { errorAjx(xhr); }
	});
	
	//取得子系統下對應的SVN交付repository連線
	changeSubsys();
	
	
	$("#btnAddSVNF").bind("click", function(){
		clearErrorMsg();
		selSVNfile("OL",$("select#subsysId option:selected").val());
	});
	
	$("#btnSubmit").bind("click", function(){
		clearErrorMsg();
		windowFreeze();
		
		var isReqExisted = false;
		var isNotBreak = 0;
		$("tr.req").each(function(){	//檢查有沒有輸入需求
			var reqSID = $(this).children("th:first").children("input").val();
			var reqDesc = $(this).children("th:last").children("textarea").val();
			
			if( $.trim(reqSID) !="" && $.trim(reqDesc) !="" ) {
				isReqExisted = true;
				$.ajax({type:"post",url:"IsReqDuplicate",dataType: "text",async:false,
					data:{reqSID:reqSID,reqDesc:reqDesc},
					success : function(res) {
						if ( res==2 ) {	//reqSID已存在，但需求描述不是所輸入的
							isNotBreak = 2;
						}
					},error : function(xhr, ajaxOptions, thrownError) { errorAjx(xhr); }
				});
				
			} else if( $.trim(reqSID) =="" && $.trim(reqDesc) =="" ) {
				$(this).remove();
			} else {
				isNotBreak = 1;
			}
		});
		
		if( isNotBreak ==0 ) {
			if ( $("#tbodySVNF > tr").size() > 0 ) {	//起碼有輸入一個檔案
				if( isReqExisted ) {
					var svnURL = $("#svnURL").val();
					var svnID = $("#svnID").val();
					var svnPWD = $("#svnPWD").val();
					var ip = $("select#svnHost option:selected").text();
					var comment = $("textarea#comment").val();
					var files = [];
					var reqs = [];
							
					$(".fileInfo").each(function(){
						var file = $(this).children("td:last").html();
						var depFile = $(this).children("td:last").attr("title");
						var ver = $(this).children("td:eq(2)").children("select").children("option:selected").val();
						files.push({"s1":depFile,"s2":file,"i1":ver});	
					});
							
					$("tr.req").each(function(){
						var reqSID = $(this).children("th:first").children("input").val();
						var reqDesc = $(this).children("th:last").children("textarea").val();
						reqs.push({"reqSID":reqSID,"reqDesc":reqDesc});
					});
					
					var fOrderDeliver = {"comment":comment,"svnURL":svnURL,"svnID":svnID,"svnPWD":svnPWD,"files":files,"reqs":reqs };
					var svnUrl = $("#svnURL").val();
					var svnId = $("#svnID").val();
					var svnPwd = $("#svnPWD").val();
					
					$.ajax({type:"post",url:"Notice2Deliver",dataType: "text",async:false,
						data:{svnUrl:svnUrl,svnId:svnId,svnPwd:svnPwd,isFTP:false,fOrderDeliver:JSON.stringify(fOrderDeliver),localSystemId:$.cookie("localSystemId"),localSystemName:$.cookie("localSystemName"),empId:$.cookie("empId"),empName:$.cookie("empName"),subsysId:$("select#subsysId").val(),targetSystemId:$("#targetSystem option:selected").attr("value")},
						success : function(res) {
							var tmp = res;
							if( tmp == "OK" ) {
								windowUnfreeze();
								alert("成功");
							} else {
								$("#errShortMsg").html("出現錯誤");
								$("#errLongMsg").html(tmp);
							}
						},error : function(xhr, ajaxOptions, thrownError) { errorAjx(xhr); }
					});
				} else {
					$("#errShortMsg").html("至少輸入一筆需求");
				}
			} else {
				$("#errShortMsg").html("起碼要選擇一個檔案");
			}
		} else if (isNotBreak==1) {
			$("#errShortMsg").html("需求資訊輸入不完整");
		} else if (isNotBreak==2) {
			$("#errShortMsg").html("這個需求編號，和以往輸入的修改內容不同");
		}
		windowUnfreeze();
	});
	
	$("#btnAddReq").bind("click",function(){
		var tmp="<tr class='req'><td class='center engN'><button type='button' onclick='removeReq(this)'>-</button></td><td class='idx int center'>"+($("#tbodyReqs tr").size()+1)+"</td><th><input class='engN' type='text' size='14'/></th><th class='zhTwN'><textarea cols='100'></textarea></th></tr>"
		$("#tbodyReqs").append(tmp);
		refreshUI(1,"tbodyReqs",false);
	});
	
	
	$("button").button();
});
</script>

</head>
<body>
	<div id="header"></div>
	
	<p>
	<img src="pic/delivery.png" > 
	<p>
	
	<button type="button" id="btnSubmit">送出</button>
	
	<p>
	
	<table id="tableFile">
		<thead class="tableFirst">
			<tr><th class="zhTwN">註解：</th><th colspan="2" class="zhTwN right">交付目標：</th><td class="left"><SELECT onchange="changeTargetSys()" id="targetSystem" class="zhTwN"></SELECT></td></tr>
			<tr><td rowspan="5"><textarea id="comment" rows="6" class="zhTwN"></textarea></td><th colspan="2" class="zhTwN right">交付系統：</th><td class="left"><select onchange="changeSubsys()" id="subsysId"></select></td></tr>
			<tr><th colspan="2" class="zhTwN right">SVN主機：</th><td class="left"><SELECT id="svnHost" onchange="changeSVNinf()" class="zhTwN"></SELECT></td></tr>
			<tr><th rowspan="3" class="zhTwN center">SVN相關</th><th class="engN right">URL：</th><td class="left"><input id="svnURL" class="engN ftp" type="text" size="14" maxlength="15" /></td></tr>
			<tr><th class="engN right">帳號：</th><td class="left"><input id="svnID" class="engN ftp" type="text"/></td></tr>
			<tr><th class="engN right">密碼：</th><td class="left"><input id="svnPWD" class="ftp" type="password"/></td></tr>
		</thead>
	</table>
	<p>	
	<table id="tableSVNF">
		<thead class="tableFirst">
			<tr><td class="center engN"><button type="button" id="btnAddSVNF">+</button></td><th class="engN">#</th><th class="zhTwN">版次</th><th class="zhTwN">檔案</th></tr>
		</thead>
		<tbody id="tbodySVNF"></tbody>
	</table>
	
	<p>	
	<table id="tableReqs">
		<thead class="tableFirst">
			<tr><td class="center engN"><button type="button" id="btnAddReq">+</button></td><th class="engN">#</th><th class="zhTwN">需求編號</th><th class="zhTwN">修改內容</th></tr>
		</thead>
		<tbody id="tbodyReqs"></tbody>
	</table>
</body>

<div class="dialog" id="dialogSVNdirectory">
	<ul id="treeDirectory" class="ztree"></ul>
</div>
</html>